package sms

import (
	"encoding/json"
	"errors"
	"gitee.com/sansaniot/ssiot-core/msg/msgtype"
	"gitee.com/sansaniot/ssiot-core/msg/sms/model"
	"gitee.com/sansaniot/ssiot-core/msg/sms/sdk/ali"
	"gitee.com/sansaniot/ssiot-core/msg/sms/sdk/jumeng"
	"gitee.com/sansaniot/ssiot-core/storage/i18n"
	"gitee.com/sansaniot/ssiot-core/utils"
	"strings"
)

var smsConfig *model.SMSConfig

func SendSMSByData(smsData model.SMSCustParam) (err error) {
	if len(smsData.Phone) == 0 {
		return errors.New("手机号不能为空")
	}

	if smsConfig.Vendor == model.Vendor_JUMENG {
		//todo 当前仅支持告警消息，后续需要结合业务平台做告警模版管理
		//生成短信内容
		content := appendAlarmContent(smsData.Param)

		//更新内容变量
		content = strings.ReplaceAll(content, "${sn}", utils.If(smsData.Param["devName"] != "", smsData.Param["devName"], smsData.Param["devSn"] != "").(string))
		content = strings.ReplaceAll(content, "${variableName}", smsData.Param["variableName"])
		content = strings.ReplaceAll(content, "${alarmType}", smsData.Param["alarmType"])
		content = strings.ReplaceAll(content, "${alarmLevel}", smsData.Param["alarmLevel"])
		content = strings.ReplaceAll(content, "${currentVal}", smsData.Param["currentVal"])
		sdk := jumeng.Sdk{Config: smsConfig}
		_, err := sdk.SendSms(strings.Join(smsData.Phone, ","), content)
		return err
	} else {
		data, _ := json.Marshal(smsData.Param)
		smsParam := string(data)

		phone := strings.Join(smsData.Phone, ",")
		sdk := ali.Sdk{Config: smsConfig}
		return sdk.SendSms(phone, smsData.Code, smsParam)
	}
}
func appendAlarmContent(param map[string]string) string {
	content := "您好，设备（${sn}）"
	if param["variableName"] != "" {
		content += "的${variableName}"
	}
	content += "产生告警，建议尽快处理。"
	appd := make([]string, 0)
	if param["alarmType"] != "" {
		appd = append(appd, "\n告警类型：${alarmType}")
	}
	if param["alarmLevel"] != "" {
		appd = append(appd, "\n告警级别：${alarmLevel}")
	}
	if param["timestamp"] != "" {
		appd = append(appd, "\n告警时间：${timestamp}")
	}
	if param["currentVal"] != "" {
		appd = append(appd, "\n告警值：${currentVal}")
	}
	content += strings.Join(appd, ", ")
	return content
}

// 短信发送示例:
//
//	sms.SendSMS(sms.SMSParam{
//		Phone: "15527557427",
//		Code:  "8888",
//	})
func SendSMS(smsData model.SMSParam, msgCode ...string) (err error) {
	if smsConfig.Vendor == model.Vendor_JUMENG {
		//content := fmt.Sprintf("您的验证码为：%s，该验证码5分钟内有效，请勿泄露给他人。", smsData.Data)
		content := i18n.Tf("", `sms_captcha`, smsData.Data)
		sdk := jumeng.Sdk{Config: smsConfig}
		_, err := sdk.SendSms(smsData.Phone, content)
		return err
	} else {
		//获取短信模版
		code := msgCode[0]
		mstType := msgtype.GetMessage(code)

		//绑定参数
		param := make(map[string]string)
		if code == msgtype.RegCode.MsgCode {
			param["captcha"] = smsData.Data
		} else if code == msgtype.ApproveOk.MsgCode {
			param["userName"] = smsData.Data
		} else if code == msgtype.ApproveReject.MsgCode {
			if len(smsData.Data) == 0 {
				smsData.Data = "400-00-64288"
			}
			param["phone"] = smsData.Data
		}
		data, _ := json.Marshal(param)
		templateParam := string(data)
		aliSdk := ali.Sdk{Config: smsConfig}
		return aliSdk.SendSms(smsData.Phone, mstType.TemplateCode, templateParam)
	}
}
func InitSMSConfig(conf *model.SMSConfig) error {
	if conf == nil {
		return errors.New("短信服务未配置。")
	} else {
		smsConfig = conf
	}
	return nil
}
